﻿@{
    Layout = null;
    string orderStatusJson = System.Text.Json.JsonSerializer.Serialize(
        ViewBag.OrderStatusList ?? new List<Model.WmsDictData>(),
        new System.Text.Json.JsonSerializerOptions
        {
            ReferenceHandler = System.Text.Json.Serialization.ReferenceHandler.IgnoreCycles,
            Encoder = System.Text.Encodings.Web.JavaScriptEncoder.UnsafeRelaxedJsonEscaping
        }
    );
    string stockInTypeStatusListJson = System.Text.Json.JsonSerializer.Serialize(
        ViewBag.StockInTypeStatusList ?? new List<Model.WmsDictData>(),
        new System.Text.Json.JsonSerializerOptions
        {
            ReferenceHandler = System.Text.Json.Serialization.ReferenceHandler.IgnoreCycles,
            Encoder = System.Text.Encodings.Web.JavaScriptEncoder.UnsafeRelaxedJsonEscaping
        }
    );
}

<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="utf-8" />
    <title>进货订单</title>
    <script src="https://unpkg.com/vue@3/dist/vue.global.js"></script>
    <script src="https://unpkg.com/axios/dist/axios.min.js"></script>
    <link rel="stylesheet" href="//unpkg.com/element-plus/dist/index.css" />
    <script src="//unpkg.com/element-plus"></script>
    <style>
        #tableBlock {
            margin: 0 auto;
            width: 1700px;
            padding-bottom: 20px;
            box-shadow: 0 0 10px 4px rgba(0, 0, 0, 0.1);
            background-color: #fff;
        }

            #tableBlock label {
                font-size: 24px;
            }

        .formTableInput, .formTableSelect {
            display: inline-block;
            width: 180px;
        }

        .buttonBlock {
            height: 40px;
            width: 100%;
            padding-top: 10px;
            padding-left: 20px;
        }

        .pagination-container {
            margin-top: 20px;
            display: flex;
            justify-content: flex-end;
        }
        /* 模态框文本域样式优化 */
        .audit-textarea {
            margin-top: 15px;
            width: 100%;
        }
        /* 操作列按钮间距 */
        .operate-btn {
            margin-right: 8px;
        }

        .btnAndTable {
            margin: 0 auto;
            margin-left: 50px;
        }
    </style>
</head>
<body>
    <div id="app" class="common-layout"
         data-order-status="@orderStatusJson"
         data-stock-in-type-status="@stockInTypeStatusListJson">
        <div id="tableBlock">
            <form>
                <table width="1700px" height="80px">
                    <tbody>
                        <tr style="background-color: #fff;">
                            <td height="40px" width="280px">
                                &nbsp;&nbsp;&nbsp;&nbsp<span>进货单号</span>&nbsp;&nbsp;&nbsp;&nbsp;
                                <el-input type="text" id="orderNoInput" class="formTableInput" placeholder="请输入"></el-input>
                            </td>
                            <td height="40px" width="280px">
                                <span>入库类型</span>&nbsp;&nbsp;&nbsp;&nbsp;
                                <el-select v-model="selectedStockInType"
                                           class="formTableSelect"
                                           placeholder="请选择入库类型">
                                    <el-option v-for="(item, index) in stockInTypeStatusList"
                                               :key="index"
                                               :label="item.Name"
                                               :value="item.Code">
                                    </el-option>
                                </el-select>
                            </td>
                            <td height="40px" width="280px">
                                <span>单据状态</span>&nbsp;&nbsp;&nbsp;&nbsp;
                                <el-select v-model="selectedOrderStatus"
                                           class="formTableSelect"
                                           placeholder="请选择单据状态">
                                    <!-- 仅渲染指定4种状态 -->
                                    <el-option v-for="(item, index) in orderStatusList.filter(s =>
                                        ['草稿', '待审核', '驳回', '已完成'].includes(s.Name)
                                       )"
                                               :key="index"
                                               :label="item.Name"
                                               :value="item.Code">
                                    </el-option>
                                </el-select>
                            </td>
                            <td height="40px" width="280px">
                                <span>进货日期</span>&nbsp;&nbsp;&nbsp;&nbsp;
                                <el-date-picker id="dateRangePicker" class="formTableInput"
                                                type="daterange"
                                                range-separator="至"
                                                start-placeholder="开始时间"
                                                end-placeholder="结束时间"
                                                :size="size" />
                            </td>
                            <td height="40px" width="160px">
                                <el-button type="reset" v-on:click="resetForm">重置</el-button>&nbsp;
                                <el-button type="primary" v-on:click="searchTable">查询</el-button>
                            </td>
                        </tr>
                    </tbody>
                </table>
            </form>
            <div class="btnAndTable">
                <!-- 顶部操作栏：保留撤销按钮 -->
                <div class="buttonBlock">
                    <el-button type="primary" v-on:click="addOrder">新增</el-button>&nbsp;
                    <el-button type="danger" v-on:click="deleteOrder">删除</el-button>&nbsp;
                    <el-button type="default" v-on:click="copyOrder">复制</el-button>&nbsp;
                    <el-button type="danger" v-on:click="openAuditModal">审核</el-button>&nbsp;
                    <el-button type="danger" v-on:click="cancleBtn">撤销</el-button>&nbsp;
                    <el-button type="default" v-on:click="exportTable">导出</el-button>&nbsp;
                    <el-button type="success" v-on:click="refrushTable">刷新</el-button>&nbsp;
                </div>
                <!-- 表格：操作列保留单行撤销 -->
                <el-table :data="paginatedData"
                          style="width: 1600px; margin-top: 10px"
                          v-on:selection-change="handleSelectionChange"
                          ref="multipleTable"
                          stripe>
                    <el-table-column fixed type="selection" width="50"></el-table-column>
                    <el-table-column fixed prop="stockInNo" label="入库单号" width="140"></el-table-column>
                    <el-table-column fixed prop="stockInType" label="入库类型" width="100"></el-table-column>
                    <el-table-column fixed prop="orderStatus" label="状态" width="150"></el-table-column>
                    <el-table-column fixed prop="stockInDate" label="入库日期" width="150"></el-table-column>
                    <el-table-column prop="warehouseName" label="仓库名称" width="120"></el-table-column>
                    <el-table-column prop="relatedOrderNo" label="关联单号" width="120"></el-table-column>
                    <el-table-column prop="stockInGoods" label="入库货品" width="120"></el-table-column>
                    <el-table-column prop="operator" label="经办人" width="200"></el-table-column>
                    <el-table-column prop="stockInQuantity" label="入库数量" width="120"></el-table-column>
                    <el-table-column prop="stockInAmount" label="入库金额" width="120"></el-table-column>
                    <el-table-column prop="creator" label="制单人" width="120"></el-table-column>
                    <el-table-column prop="deptName" label="所在部门" width="120"></el-table-column>
                    <el-table-column prop="createTime" label="制单时间" width="120"></el-table-column>
                    <el-table-column prop="auditor" label="审核人" width="120"></el-table-column>
                    <el-table-column prop="auditTime" label="审核时间" width="120"></el-table-column>
                    <el-table-column fixed="right" label="操作" min-width="180">
                        <template #default="scope">
                            <!-- 草稿/待审核/驳回：编辑、删除 -->
                            <el-button v-if="['草稿', '待审核', '驳回'].includes(scope.row.orderStatus)"
                                       class="operate-btn"
                                       link type="primary" size="default"
                                       v-on:click="handleEdit(scope.row)">
                                编辑
                            </el-button>
                            <el-button v-if="['草稿', '待审核', '驳回'].includes(scope.row.orderStatus)"
                                       class="operate-btn"
                                       link type="danger" size="default"
                                       v-on:click="deleteSingleOrder(scope.row)">
                                删除
                            </el-button>
                            <!-- 驳回：单行撤销（与顶部批量撤销逻辑一致） -->
                            <el-button v-if="scope.row.orderStatus === '驳回'"
                                       class="operate-btn"
                                       link type="warning" size="default"
                                       v-on:click="rejectCancel(scope.row)">
                                撤销
                            </el-button>
                            <!-- 已完成：无操作 -->
                            <span v-if="scope.row.orderStatus === '已完成'">-</span>
                        </template>
                    </el-table-column>
                </el-table>
            </div>
            <div class="pagination-container">
                <el-pagination v-model:current-page="currentPage"
                               v-model:page-size="pageSize"
                               :page-sizes="[10, 20, 50, 100]"
                               :total="total"
                               layout="total, sizes, prev, pager, next, jumper"
                               v-on:size-change="handleSizeChange"
                               v-on:current-change="handleCurrentChange">
                </el-pagination>
            </div>
        </div>
        <!-- 审核模态框 -->
        <el-dialog title="订单审核"
                   v-model="isAuditModalOpen"
                   width="500px"
                   :before-close="handleAuditModalClose">
            <div class="audit-content">
                <el-radio-group v-model="selectedAuditResult" required>
                    <el-radio label="pass">通过（转为已完成）</el-radio>
                    <el-radio label="reject">驳回</el-radio>
                </el-radio-group>
                <el-input class="audit-textarea"
                          type="textarea"
                          v-model="auditOpinion"
                          placeholder="请输入审核意见（驳回时必填）"
                          :rows="4"
                          :maxlength="200"
                          show-word-limit></el-input>
            </div>
            <template #footer>
                <el-button v-on:click="isAuditModalOpen = false">取消</el-button>
                <el-button type="primary" v-on:click="confirmAudit">确认审核</el-button>
            </template>
        </el-dialog>
    </div>

    <script>
        const { createApp, ref, onMounted, computed } = Vue;
        const { ElMessageBox, ElMessage, ElNotification } = ElementPlus;
        const app = createApp({
            setup() {
                // -------------------------- 1. 基础数据初始化 --------------------------
                // 单据状态字典
                const orderStatusListStr = document.getElementById('app').dataset.orderStatus || '[]';
                const orderStatusList = ref([]);
                try {
                    let parseData = JSON.parse(orderStatusListStr);
                    parseData = parseData.filter(item => ['草稿', '待审核', '驳回', '已完成'].includes(item.Name));
                    orderStatusList.value = Array.isArray(parseData) ? parseData : [];
                } catch (e) {
                    console.error('解析单据状态字典失败：', e);
                    orderStatusList.value = [];
                }

                // 入库类型字典
                const stockInTypeStatusListStr = document.getElementById('app').dataset.stockInTypeStatus || '[]';
                const stockInTypeStatusList = ref([]);
                try {
                    const parseData = JSON.parse(stockInTypeStatusListStr);
                    stockInTypeStatusList.value = Array.isArray(parseData) ? parseData : [];
                } catch (e) {
                    console.error('解析入库类型字典失败：', e);
                    stockInTypeStatusList.value = [];
                }


                // -------------------------- 2. 表格模拟数据：新增rejectPrevStatus字段记录驳回前状态 --------------------------
                const tableData = ref([
                    {
                        stockInNo: 'IN-202405001',
                        stockInType: '采购入库',
                        orderStatus: '草稿',
                        rejectPrevStatus: '', // 非驳回状态，为空
                        stockInDate: '2024-05-03',
                        warehouseName: '主仓库',
                        relatedOrderNo: 'PO-202404001',
                        stockInGoods: '笔记本电脑',
                        operator: '李四',
                        stockInQuantity: 50,
                        stockInAmount: 25000,
                        creator: '张三',
                        deptName: '采购一部',
                        createTime: '2024-05-03 09:30',
                        auditor: '',
                        auditTime: '',
                        rejectReason: ''
                    },
                    {
                        stockInNo: 'IN-202405002',
                        stockInType: '退货入库',
                        orderStatus: '待审核',
                        rejectPrevStatus: '', // 非驳回状态，为空
                        stockInDate: '2024-05-02',
                        warehouseName: '副仓库',
                        relatedOrderNo: 'PO-202404002',
                        stockInGoods: '无线键盘',
                        operator: '赵六',
                        stockInQuantity: 30,
                        stockInAmount: 2697,
                        creator: '王五',
                        deptName: '采购二部',
                        createTime: '2024-05-02 14:20',
                        auditor: '',
                        auditTime: '',
                        rejectReason: ''
                    },
                    {
                        stockInNo: 'IN-202405003',
                        stockInType: '采购入库',
                        orderStatus: '驳回',
                        rejectPrevStatus: '待审核', // 记录驳回前状态（关键）
                        stockInDate: '2024-05-01',
                        warehouseName: '主仓库',
                        relatedOrderNo: 'PO-202404003',
                        stockInGoods: '激光打印机',
                        operator: '周八',
                        stockInQuantity: 10,
                        stockInAmount: 12990,
                        creator: '孙七',
                        deptName: '采购一部',
                        createTime: '2024-05-01 16:45',
                        auditor: '钱十一',
                        auditTime: '2024-05-01 17:00',
                        rejectReason: '货品规格填写错误'
                    },
                    {
                        stockInNo: 'IN-202405004',
                        stockInType: '调拨入库',
                        orderStatus: '已完成',
                        rejectPrevStatus: '', // 非驳回状态，为空
                        stockInDate: '2024-04-30',
                        warehouseName: '主仓库',
                        relatedOrderNo: 'TR-202404001',
                        stockInGoods: '投影仪',
                        operator: '郑十',
                        stockInQuantity: 8,
                        stockInAmount: 15920,
                        creator: '吴九',
                        deptName: '仓储部',
                        createTime: '2024-04-30 11:10',
                        auditor: '钱十一',
                        auditTime: '2024-04-30 11:30',
                        rejectReason: ''
                    },
                    {
                        stockInNo: 'IN-202405005',
                        stockInType: '采购入库',
                        orderStatus: '驳回',
                        rejectPrevStatus: '草稿', // 记录驳回前状态（关键）
                        stockInDate: '2024-04-29',
                        warehouseName: '副仓库',
                        relatedOrderNo: 'PO-202404004',
                        stockInGoods: '显示器',
                        operator: '冯十二',
                        stockInQuantity: 20,
                        stockInAmount: 11980,
                        creator: '钱十一',
                        deptName: '采购二部',
                        createTime: '2024-04-29 15:50',
                        auditor: '孙七',
                        auditTime: '2024-04-29 16:00',
                        rejectReason: '供应商信息不全'
                    }
                ]);

                // 基础变量：selectedRows（选中行）、rejectPrevStatusMap（备用状态记录，防止数据丢失）
                const selectedRows = ref([]);
                const multipleTable = ref(null);
                const selectedStockInType = ref('');
                const selectedOrderStatus = ref('');
                const rejectPrevStatusMap = ref({}); // 存储驳回前状态的备用映射（key：入库单号，value：驳回前状态）


                // -------------------------- 3. 分页逻辑 --------------------------
                const currentPage = ref(1);
                const pageSize = ref(10);
                const total = computed(() => tableData.value.length);
                const paginatedData = computed(() => {
                    const start = (currentPage.value - 1) * pageSize.value;
                    const end = start + pageSize.value;
                    return tableData.value.slice(start, end);
                });

                const handleSizeChange = (val) => {
                    pageSize.value = val;
                    currentPage.value = 1;
                };

                const handleCurrentChange = (val) => {
                    currentPage.value = val;
                    multipleTable.value?.clearSelection();
                    selectedRows.value = [];
                };


                // -------------------------- 4. 审核模态框：驳回时记录原始状态 --------------------------
                const isAuditModalOpen = ref(false);
                const selectedAuditResult = ref('');
                const auditOpinion = ref('');
                const canAuditRows = ref([]);

                const openAuditModal = () => {
                    if (selectedRows.value.length === 0) {
                        ElMessage({ type: 'warning', message: '请先选中需要审核的订单！' });
                        return;
                    }
                    canAuditRows.value = selectedRows.value.filter(row => row.orderStatus === '待审核');
                    if (canAuditRows.value.length === 0) {
                        ElMessage({ type: 'error', message: '选中的订单中无「待审核」状态订单！' });
                        return;
                    }
                    selectedAuditResult.value = '';
                    auditOpinion.value = '';
                    isAuditModalOpen.value = true;
                };

                const handleAuditModalClose = () => {
                    selectedAuditResult.value = '';
                    auditOpinion.value = '';
                    isAuditModalOpen.value = false;
                };

                const confirmAudit = () => {
                    if (!selectedAuditResult.value) {
                        ElMessage({ type: 'warning', message: '请选择审核结果（通过/驳回）！' });
                        return;
                    }
                    if (selectedAuditResult.value === 'reject' && !auditOpinion.value.trim()) {
                        ElMessage({ type: 'warning', message: '驳回订单时必须填写审核意见！' });
                        return;
                    }

                    const auditIds = canAuditRows.value.map(row => row.stockInNo).join(',');
                    ElMessageBox.confirm(
                        `确定${selectedAuditResult.value === 'pass' ? '通过' : '驳回'}选中的 ${canAuditRows.value.length} 条订单吗？`,
                        '确认审核',
                        { type: selectedAuditResult.value === 'pass' ? 'info' : 'warning' }
                    ).then(() => {
                        tableData.value.forEach(row => {
                            if (auditIds.includes(row.stockInNo)) {
                                if (selectedAuditResult.value === 'reject') {
                                    // 关键：驳回时，记录当前状态为“驳回前状态”
                                    row.rejectPrevStatus = row.orderStatus; // 存到数据行
                                    rejectPrevStatusMap.value[row.stockInNo] = row.orderStatus; // 存到备用映射
                                }
                                // 更新状态和审核信息
                                row.orderStatus = selectedAuditResult.value === 'pass' ? '已完成' : '驳回';
                                row.auditor = '当前登录用户';
                                row.auditTime = new Date().toLocaleString('zh-CN', { hour12: false });
                                if (selectedAuditResult.value === 'reject') row.rejectReason = auditOpinion.value;
                            }
                        });
                        ElMessage({
                            type: 'success',
                            message: `订单${selectedAuditResult.value === 'pass' ? '审核通过（已转为已完成）' : '审核驳回'}成功！`
                        });
                        multipleTable.value?.clearSelection();
                        selectedRows.value = [];
                        handleAuditModalClose();
                    }).catch(() => {
                        ElMessage({ type: 'info', message: '已取消审核' });
                    });
                };


                // -------------------------- 5. 核心操作：顶部批量撤销（cancleBtn）+ 单行撤销（rejectCancel） --------------------------
                // 5.1 选中行变化
                const handleSelectionChange = (val) => {
                    selectedRows.value = val;
                };

                // 5.2 顶部批量撤销按钮：cancleBtn（核心功能）
                const cancleBtn = () => {
                    // 校验1：是否选中订单
                    if (selectedRows.value.length === 0) {
                        ElMessage({ type: 'warning', message: '请先选中需要撤销的订单！' });
                        return;
                    }
                    // 校验2：选中的是否都是“驳回”状态
                    const canCancelRows = selectedRows.value.filter(row => row.orderStatus === '驳回');
                    if (canCancelRows.length === 0) {
                        ElMessage({ type: 'error', message: '仅「驳回」状态的订单可执行撤销操作！' });
                        return;
                    }
                    // 校验3：是否都有驳回前状态记录
                    const validCancelRows = canCancelRows.filter(row =>
                        row.rejectPrevStatus || rejectPrevStatusMap.value[row.stockInNo]
                    );
                    if (validCancelRows.length === 0) {
                        ElMessage({ type: 'error', message: '部分订单缺少驳回前状态记录，无法撤销！' });
                        return;
                    }

                    // 批量撤销确认：显示包含原始状态的提示
                    const cancelIds = validCancelRows.map(row => row.stockInNo).join(',');
                    ElMessageBox.confirm(
                        `确定撤销选中的 ${validCancelRows.length} 条驳回订单吗？撤销后将恢复至驳回前状态（如：待审核/草稿）！`,
                        '确认批量撤销',
                        { type: 'warning' }
                    ).then(() => {
                        tableData.value.forEach(row => {
                            if (cancelIds.includes(row.stockInNo)) {
                                // 恢复至驳回前状态（优先用数据行的rejectPrevStatus，备用映射兜底）
                                const prevStatus = row.rejectPrevStatus || rejectPrevStatusMap.value[row.stockInNo];
                                row.orderStatus = prevStatus;
                                // 清空驳回相关信息
                                row.auditor = '';
                                row.auditTime = '';
                                row.rejectReason = '';
                                row.rejectPrevStatus = ''; // 清空状态记录字段
                                delete rejectPrevStatusMap.value[row.stockInNo]; // 清空备用映射
                            }
                        });
                        ElMessage({ type: 'success', message: `批量撤销成功！${validCancelRows.length} 条订单已恢复至驳回前状态` });
                        multipleTable.value?.clearSelection();
                        selectedRows.value = [];
                    }).catch(() => {
                        ElMessage({ type: 'info', message: '已取消批量撤销' });
                    });
                };

                // 5.3 单行撤销：rejectCancel（与批量撤销逻辑一致，支持单行操作）
                const rejectCancel = (row) => {
                    // 校验1：是否为驳回状态
                    if (row.orderStatus !== '驳回') {
                        ElMessage({ type: 'error', message: '仅「驳回」状态订单可执行撤销操作！' });
                        return;
                    }
                    // 校验2：是否有驳回前状态记录
                    const prevStatus = row.rejectPrevStatus || rejectPrevStatusMap.value[row.stockInNo];
                    if (!prevStatus) {
                        ElMessage({ type: 'error', message: '该订单缺少驳回前状态记录，无法撤销！' });
                        return;
                    }

                    // 单行撤销确认：显示具体原始状态
                    const reasonTip = row.rejectReason ? `（原驳回原因：${row.rejectReason}）` : '';
                    ElMessageBox.confirm(
                        `确定撤销订单 ${row.stockInNo} 的驳回状态吗？${reasonTip} 撤销后将恢复为「${prevStatus}」状态！`,
                        '确认撤销',
                        { type: 'warning' }
                    ).then(() => {
                        // 恢复状态
                        row.orderStatus = prevStatus;
                        // 清空驳回相关信息
                        row.auditor = '';
                        row.auditTime = '';
                        row.rejectReason = '';
                        row.rejectPrevStatus = '';
                        delete rejectPrevStatusMap.value[row.stockInNo];
                        ElMessage({ type: 'success', message: `撤销成功！订单已恢复为「${prevStatus}」状态` });
                    }).catch(() => {
                        ElMessage({ type: 'info', message: '已取消撤销' });
                    });
                };

                // 5.4 编辑：草稿/待审核/驳回可编辑
                const handleEdit = (row) => {
                    if (row.orderStatus === '已完成') {
                        ElMessage({ type: 'error', message: '「已完成」状态订单不允许编辑！' });
                        return;
                    }
                    ElNotification({
                        title: '编辑订单',
                        message: `跳转至${row.stockInNo}的编辑页面`,
                        type: 'info'
                    });
                    // 实际跳转：window.location.href = `/StockIn/Edit?stockInNo=${row.stockInNo}`;
                };

                // 5.5 单行删除：草稿/待审核/驳回可删除
                const deleteSingleOrder = (row) => {
                    if (row.orderStatus === '已完成') {
                        ElMessage({ type: 'error', message: '「已完成」状态订单不允许删除！' });
                        return;
                    }
                    ElMessageBox.confirm(
                        `确定删除订单 ${row.stockInNo} 吗？删除后不可恢复！`,
                        '警告',
                        { type: 'error' }
                    ).then(() => {
                        // 删除时同步清理备用状态映射
                        delete rejectPrevStatusMap.value[row.stockInNo];
                        tableData.value = tableData.value.filter(item => item.stockInNo !== row.stockInNo);
                        ElMessage({ type: 'success', message: '删除成功！' });
                    }).catch(() => {
                        ElMessage({ type: 'info', message: '已取消删除' });
                    });
                };

                // 5.6 批量删除：草稿/待审核/驳回可批量删除
                const deleteOrder = () => {
                    if (selectedRows.value.length === 0) {
                        ElMessage({ type: 'warning', message: '请先选中需要删除的订单！' });
                        return;
                    }
                    const canDeleteRows = selectedRows.value.filter(row =>
                        ['草稿', '待审核', '驳回'].includes(row.orderStatus)
                    );
                    if (canDeleteRows.length === 0) {
                        ElMessage({ type: 'error', message: '仅「草稿」、「待审核」或「驳回」状态的订单可删除！' });
                        return;
                    }
                    const deleteIds = canDeleteRows.map(row => row.stockInNo).join(',');
                    ElMessageBox.confirm(
                        `确定删除选中的 ${canDeleteRows.length} 条订单吗？`,
                        '警告',
                        { type: 'error' }
                    ).then(() => {
                        // 批量删除时同步清理备用状态映射
                        canDeleteRows.forEach(row => delete rejectPrevStatusMap.value[row.stockInNo]);
                        tableData.value = tableData.value.filter(row => !deleteIds.includes(row.stockInNo));
                        ElMessage({ type: 'success', message: '删除成功！' });
                        selectedRows.value = [];
                    }).catch(() => {
                        ElMessage({ type: 'info', message: '已取消删除' });
                    });
                };


                // -------------------------- 6. 辅助方法 --------------------------
                // 6.1 导出
                const exportTable = () => {
                    const stockInNo = document.getElementById('orderNoInput').value.trim() || '';
                    const datePicker = document.getElementById('dateRangePicker');
                    const dateRange = datePicker && datePicker.value ? datePicker.value.join(',') : '';
                    const stockInType = selectedStockInType.value || '';
                    const orderStatus = selectedOrderStatus.value || '';

                    const exportUrl = `/api/StockIn/Export?` +
                        `stockInNo=${encodeURIComponent(stockInNo)}&` +
                        `stockInType=${encodeURIComponent(stockInType)}&` +
                        `orderStatus=${encodeURIComponent(orderStatus)}&` +
                        `dateRange=${encodeURIComponent(dateRange)}`;

                    const link = document.createElement('a');
                    link.href = exportUrl;
                    link.download = `入库订单列表_${new Date().toLocaleDateString()}.xlsx`;
                    link.click();
                    ElMessage({ type: 'success', message: '导出请求已触发，正在下载...' });
                };

                // 6.2 刷新
                const refrushTable = () => {
                    multipleTable.value?.clearSelection();
                    selectedRows.value = [];
                    currentPage.value = 1;
                    ElMessage({ type: 'success', message: '表格已刷新！' });
                };

                // 6.3 重置表单
                const resetForm = () => {
                    document.getElementById('orderNoInput').value = '';
                    document.getElementById('dateRangePicker').value = '';
                    selectedStockInType.value = '';
                    selectedOrderStatus.value = '';
                };

                // 6.4 查询
                const searchTable = () => {
                    const stockInNo = document.getElementById('orderNoInput').value.trim() || '';
                    const stockInType = selectedStockInType.value || '';
                    const orderStatus = selectedOrderStatus.value || '';
                    const datePicker = document.getElementById('dateRangePicker');
                    const dateRange = datePicker && datePicker.value ? datePicker.value : [];
                    const startDate = dateRange[0] || '';
                    const endDate = dateRange[1] || '';

                    const filteredData = tableData.value.filter(row => {
                        const matchNo = stockInNo ? row.stockInNo.includes(stockInNo) : true;
                        const matchType = stockInType ? row.stockInType === stockInType : true;
                        const matchStatus = orderStatus ? row.orderStatus === orderStatus : true;
                        const matchDate = !startDate || !endDate
                            ? true
                            : (row.stockInDate >= startDate && row.stockInDate <= endDate);

                        return matchNo && matchType && matchStatus && matchDate;
                    });

                    tableData.value = filteredData;
                    currentPage.value = 1;
                    ElMessage({ type: 'success', message: `查询到 ${filteredData.length} 条数据！` });
                };

                // 6.5 新增
                const addOrder = () => {
                    ElNotification({ title: '提示', message: '跳转至新增订单页面', type: 'info' });
                    window.location.href = '/StockUpOrder/AddIndex';
                };

                // 6.6 复制
                const copyOrder = () => {
                    if (selectedRows.value.length === 0) {
                        ElMessage({ type: 'warning', message: '请先选中需要复制的订单！' });
                        return;
                    }
                    if (selectedRows.value.length > 1) {
                        ElMessage({ type: 'warning', message: '仅支持单条订单复制！' });
                        return;
                    }
                    const targetRow = selectedRows.value[0];
                    if (targetRow.orderStatus === '已完成') {
                        ElMessage({ type: 'error', message: '「已完成」状态的订单不支持复制！' });
                        return;
                    }
                    ElNotification({ title: '复制订单', message: `开始复制订单：${targetRow.stockInNo}`, type: 'info' });
                };


                // -------------------------- 7. 页面挂载 --------------------------
                onMounted(() => {
                    // 初始化备用状态映射（从模拟数据中读取已有的驳回前状态）
                    tableData.value.forEach(row => {
                        if (row.orderStatus === '驳回' && row.rejectPrevStatus) {
                            rejectPrevStatusMap.value[row.stockInNo] = row.rejectPrevStatus;
                        }
                    });
                    // 单据状态默认选中第一项
                    if (orderStatusList.value.length > 0) {
                        selectedOrderStatus.value = orderStatusList.value[0].Code;
                    }
                    // 入库类型默认选中第一项
                    if (stockInTypeStatusList.value.length > 0) {
                        selectedStockInType.value = stockInTypeStatusList.value[0].Code;
                    }
                });


                // -------------------------- 8. 暴露数据和方法 --------------------------
                return {
                    // 表格相关
                    tableData,
                    paginatedData,
                    selectedRows,
                    multipleTable,
                    handleSelectionChange,
                    handleEdit,
                    deleteSingleOrder,
                    rejectCancel,

                    // 字典数据
                    orderStatusList,
                    stockInTypeStatusList,
                    selectedStockInType,
                    selectedOrderStatus,

                    // 分页相关
                    currentPage,
                    pageSize,
                    total,
                    handleSizeChange,
                    handleCurrentChange,

                    // 审核模态框相关
                    isAuditModalOpen,
                    selectedAuditResult,
                    auditOpinion,
                    openAuditModal,
                    handleAuditModalClose,
                    confirmAudit,

                    // 按钮方法（含顶部批量撤销cancleBtn）
                    addOrder,
                    deleteOrder,
                    copyOrder,
                    cancleBtn,
                    exportTable,
                    refrushTable,
                    resetForm,
                    searchTable
                };
            }
        });
        app.use(ElementPlus);
        app.mount('#app');
    </script>
</body>
</html>